package com.base.utils;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.base.comm.CommUrls;

public class DatabaseUtil {
	/**
	 * java 查询mysql数据库字段容量
	 * 
	 * @return
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public static Integer getFieldCapacity() {
		//查询到的数据
		List<String> capacity =new ArrayList<String>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = (Connection) DriverManager.getConnection(CommUrls.JDBC, CommUrls.JDBC_USER, CommUrls.JDBC_PASSWORD);
		
			//查询字段容量 sql语句
			String sql = "SHOW VARIABLES LIKE '%max_allowed_packet%'";
			pstmt = (PreparedStatement)conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			int col = rs.getMetaData().getColumnCount();
			
			//循环查询到的值 取到value
			while (rs.next()) {
	            for (int i = 1; i <= col; i++) {
	            	if(i == 2) {
	            		capacity.add(rs.getString("value"));
	            	}
	             }
	        }
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		
		if(capacity != null && capacity.size() > 0) {
			return Integer.parseInt(capacity.get(0));
		}else {
			return null;
		}
	}
}
